const { ethers, network } = require("hardhat")
// const { keccak256, toUtf8Bytes } = require("ethers") // v6

async function mockKeepers() {
    const raffle = await ethers.getContract("Raffle")
    // const checkData = ethers.utils.keccak256(ethers.utils.toUtf8Bytes("")) // v5
    const checkData = keccak256(toUtf8Bytes("")) // v6
    // const { upkeepNeeded } = await raffle.callStatic.checkUpkeep(checkData) // v5
    const [upkeepNeeded, performData] = await raffle.checkUpkeep.staticCall("0x")
    console.log("upkeepNeeded:", upkeepNeeded)
    console.log("performData:", performData)

    const raffleState = await raffle.getRaffleState()
    const interval = await raffle.getInterval()
    const lastTime = await raffle.getLastTimeStamp()
    const players = await raffle.getNumberOfPlayers()
    const balance = await ethers.provider.getBalance(raffle.target)

    console.log("raffleState:", raffleState.toString())  // 应该是 0 (OPEN)
    const now = BigInt(Math.floor(Date.now() / 1000))
    console.log("timePassed:", now - lastTime > interval)
    console.log("players:", players.toString())
    console.log("balance:", balance.toString())

    if (upkeepNeeded) {
        const tx = await raffle.performUpkeep(checkData)
        const txReceipt = await tx.wait(1)
        // const requestId = txReceipt.events[1].args.requestId // v5
        const requestId = txReceipt.logs[1].args.requestId // v6 logs 代替 events
        console.log(`Performed upkeep with RequestId: ${requestId}`)
        if (network.config.chainId == 31337) {
            await mockVrf(requestId, raffle)
        }
    } else {
        console.log("No upkeep needed!")
    }
}

async function mockVrf(requestId, raffle) {
    console.log("We on a local network? Ok let's pretend...")
    const vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2_5Mock")
    // await vrfCoordinatorV2Mock.fulfillRandomWords(requestId, raffle.address) // v5
    await vrfCoordinatorV2Mock.fulfillRandomWords(requestId, raffle.target) // v6
    console.log("Responded!")
    const recentWinner = await raffle.getRecentWinner()
    console.log(`The winner is: ${recentWinner}`)
}

mockKeepers()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error)
        process.exit(1)
    })

